﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HomeStayWebCP.Models;
using DAL;
using HomeStayWebCP.Models.BusinessObject;

namespace HomeStayWebCP.Controllers.Admin
{
    public class ManagePostsController : Controller
    {
        //
        // GET: /ManagePosts/
        ManagePostsModel _model = new ManagePostsModel();
        public ActionResult Index()
        {
            if (HttpContext.Session["roleID"] != null && !HttpContext.Session["roleID"].ToString().Equals(String.Empty))
            {
                return View();
            }
            else
            {
                //redirect to You doesn't have permission
                return RedirectToAction("Login", "Admin");
            } 
        }

        public ActionResult ManagePost(int status)
        {
            if (HttpContext.Session["roleID"] != null && !HttpContext.Session["roleID"].ToString().Equals(String.Empty))
            {
                HttpContext.Session["status2return"] = status;
                ViewBag.status = status;
                return PartialView("Index");
            }
            else
            {
                //redirect to You doesn't have permission
                return RedirectToAction("Login", "Admin");
            }
        }

        public ActionResult ShowListPosts(int status)
        {
            ManagePostsModel model = new ManagePostsModel();
            IList<Post_ManagePosts_View> listResultPosts = model.GetListPost(status);
            return PartialView("ManagePost", listResultPosts);
        }

        public ActionResult DatatableListPosts (int status, JQueryDataTableParamModel param)
        {
            HttpContext.Session["status2return"] = status;
            var model = new ManagePostsModel();
            var allPosts = model.GetListPost(status);
            IEnumerable<Post_ManagePosts_View> filteredListPosts;
            if (!string.IsNullOrEmpty(param.sSearch))
            {
                //Used if particulare columns are filtered 
                var provinceFilter = Convert.ToString(Request["sSearch_1"]);
                var districtFilter = Convert.ToString(Request["sSearch_2"]);
                var userFilter = Convert.ToString(Request["sSearch_3"]);

                //Optionally check whether the columns are searchable at all 
                var isTitleSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
                var isStatusSearchable = Convert.ToBoolean(Request["bSearchable_2"]);
                var isProvinceSearchable = Convert.ToBoolean(Request["bSearchable_3"]);
                var isDistrictSearchable = Convert.ToBoolean(Request["bSearchable_4"]);
                var isUserSearchable = Convert.ToBoolean(Request["bSearchable_5"]);
                var isTimecreateSearchable = Convert.ToBoolean(Request["bSearchable_6"]);

                filteredListPosts = model.GetListPost(status)
                    .Where(c => isTitleSearchable && c.Title.ToLower().Contains(param.sSearch.ToLower())
                                ||
                                isProvinceSearchable && c.Province.ToLower().Contains(param.sSearch.ToLower())
                                ||
                                isDistrictSearchable && c.District.ToLower().Contains(param.sSearch.ToLower())
                                ||
                                isUserSearchable && c.Username.ToLower().Contains(param.sSearch.ToLower()));

            }
            else
            {
                filteredListPosts = allPosts;
            }
            var isTitileSortable = Convert.ToBoolean(Request["bSortable_1"]);
            var isProvinceSortable = Convert.ToBoolean(Request["bSortable_2"]);
            var isDistrictSortable = Convert.ToBoolean(Request["bSortable_3"]);
            var isUserSortable = Convert.ToBoolean(Request["bSortable_4"]);
            var isTimecreateSortable = Convert.ToBoolean(Request["bSortable_5"]);
            var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
            Func<Post_ManagePosts_View, string> orderingFunction = (c => sortColumnIndex == 1 && isTitileSortable ? c.Title :
                                                                            sortColumnIndex == 2 && isProvinceSortable ? c.Province :
                                                                           sortColumnIndex == 3 && isDistrictSortable ? c.District :
                                                                           sortColumnIndex == 4 && isUserSortable ? c.Username :
                                                                           sortColumnIndex == 5 && isTimecreateSortable ? c.TimeCreated :
                                                           "");
            var sortDirection = Request["sSortDir_0"]; // asc or desc
            if (sortDirection == "asc")
                filteredListPosts = filteredListPosts.OrderBy(orderingFunction);
            else
                filteredListPosts = filteredListPosts.OrderByDescending(orderingFunction);

            var displayedListPosts = filteredListPosts.Skip(param.iDisplayStart).Take(param.iDisplayLength);
            var result = from c in displayedListPosts
                         select new[]
                                    {
                                        c.PostID.ToString(),
                                        c.AvatarPost,
                                        c.Title,
                                        c.IsAvailable.ToString(),
                                        c.TypeOfHousesNAME,
                                        c.Province,
                                        c.District,
                                        c.Username,
                                        c.TimeCreated
                                    }
                                    ;
            return Json(new
                            {
                                sEcho = param.sEcho,
                                iTotalRecords = allPosts.Count(),
                                iTotalDisplayRecords = filteredListPosts.Count(),
                                aaData = result
                            },
                        JsonRequestBehavior.AllowGet);

        }


        #region Khoana - Manager View Detail Of Post
        public ActionResult ManViewPost(int postID)
        {
            if (HttpContext.Session["roleID"] != null && !HttpContext.Session["roleID"].ToString().Equals(String.Empty))
            {
                HttpContext.Session.Add("PostID", postID);
                ManagePostsModel postModel = new ManagePostsModel(); //get post detail
                PostModel pModel = new PostModel();
                UserModel userModel = new UserModel();
                LikeModel likeModel = new LikeModel();
                ImageModel imageModel = new ImageModel();
                HomeStayTypeModel hsTypeModel = new HomeStayTypeModel();
                CommentModel commentModel = new CommentModel();

                PostItem postDetailInfo = postModel.ManGetDetailOfPost(postID);
                int timeRejected = 0;
                if (postDetailInfo.Status == -1)
                {
                     timeRejected = postModel.GetTimeRejectedPost(postID);
                }
                List<ImageItem> imagesOfPost = imageModel.GetImagesOfPost(postID);
                AuthorInfo author = userModel.GetAuthorOfPost(postID);
                //use to get name of region
                //regionModel.SelectNameFromID(
                int likeNumberofPost = likeModel.CountLikeOfPost(postID);



                //getHouseIF from postDetail
                //hsTypeModel.GetNameHomeStayTypeOfHouse(1);
                List<string> listTypeHomestay = pModel.getHomestayname(postID);
                List<CommentObject> commentsOfPost = commentModel.GetCommentOfPost(postID);

                //Hoangdx code Comment Function Start

                List<CommentObject> ListCommentView = new List<CommentObject>();
                CommentModel model = new CommentModel();

                //Hoangdx code Paging
                if (listTypeHomestay.Count > 0)
                {
                    ViewBag.listTypeHomestay = listTypeHomestay;
                }
                string id = null;
                int count = model.SetCountPaging(5, postID);//Step1: Get so page 
                ViewBag.ListComment = model.GetCommentOfPaing(ref id, postID);//Step 2: get data cho moi page
                ViewBag.count = count;
                ViewBag.page = id;

                //Hoangdx code Comment Function End

                ViewBag.imagesOfPost = imagesOfPost;
                ViewBag.postDetailInfo = postDetailInfo;
                ViewBag.timeRejectedPost = timeRejected;
                ViewBag.author = author;
                ViewBag.likeNumberofPost = likeNumberofPost;
                ViewBag.commentsOfPost = commentsOfPost;
                Session["ContactEmail"] = postDetailInfo.Email;
                Session["PostTitle"] = postDetailInfo.Title;
                return View();
            }
            else
            {
                //redirect to You doesn't have permission
                return RedirectToAction("Login", "Admin");
            }
            
        }
        #endregion


        #region Khoana - Accept Post
        [HttpPost]
        public ActionResult AcceptPost (int postId)
        {
            //int check;
            //check = _model.AcceptPost(postId);
            //if (Request.IsAjaxRequest())
            //{
            //    return Json(check, "application/json");
            //}
            //else
            //{
            //    return RedirectToAction("ManViewPost",postId);
            //}
            string reviewBy = HttpContext.Session["usernameAdmin"].ToString(); 
            _model.AcceptPost(postId, reviewBy);
           // ViewBag.status = 0;
            return PartialView("Index");
        }
        #endregion

        #region Khoana - Reject Post
        [HttpPost]
        public ActionResult RejectPost(int postId)
        {
            //int check;
            //check = _model.RejectPost(postId);
            //if (Request.IsAjaxRequest())
            //{
            //    return Json(check, "application/json");
            //}
            //else
            //{
            //     return RedirectToAction("ManViewPost");
            //}
            string reviewBy = HttpContext.Session["usernameAdmin"].ToString();
            _model.RejectPost(postId, reviewBy);
           // ViewBag.status = 0;
            return PartialView("Index");
        }
        #endregion

        #region KhoaNA - DeletePost
        [HttpPost]
        public ActionResult DeletePost (int postId)
        {
            _model.DeletePost(postId);
            return PartialView("Index");
        }
        #endregion


    }
}
